package com.example.lexiangbackend.controller;

import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/audio")
public class AudioProxyController {

    private final RestTemplate restTemplate;
    
    public AudioProxyController() {
        this.restTemplate = new RestTemplate();
        // 配置超时时间
        this.restTemplate.getMessageConverters().forEach(converter -> {
            if (converter instanceof org.springframework.http.converter.ByteArrayHttpMessageConverter) {
                // 增加支持的媒体类型
                ((org.springframework.http.converter.ByteArrayHttpMessageConverter) converter)
                    .setSupportedMediaTypes(java.util.Arrays.asList(
                        MediaType.APPLICATION_OCTET_STREAM,
                        MediaType.parseMediaType("audio/*"),
                        MediaType.parseMediaType("application/ogg"),
                        MediaType.parseMediaType("audio/mpeg"),
                        MediaType.parseMediaType("audio/mp3"),
                        MediaType.parseMediaType("audio/wav"),
                        MediaType.parseMediaType("audio/ogg")
                    ));
            }
        });
    }

    /**
     * 音频代理接口 - 解决跨域问题
     */
    @PostMapping("/proxy")
    public ResponseEntity<?> proxyAudio(@RequestBody Map<String, String> request) {
        try {
            String originalUrl = request.get("url");
            String platform = request.get("platform");
            
            if (originalUrl == null || originalUrl.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("URL不能为空"));
            }

            // 验证URL是否为支持的音乐平台
            if (!isSupportedMusicUrl(originalUrl)) {
                return ResponseEntity.badRequest().body(createErrorResponse("不支持的音乐平台URL"));
            }

            // 根据平台类型处理URL
            String processedUrl = processUrlByPlatform(originalUrl, platform);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "获取代理URL成功");
            response.put("proxyUrl", processedUrl);
            response.put("originalUrl", originalUrl);
            response.put("platform", platform);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("处理音频URL失败: " + e.getMessage()));
        }
    }

    /**
     * 直接代理音频流
     */
    @GetMapping("/stream")
    public ResponseEntity<byte[]> streamAudio(@RequestParam String url) {
        try {
            System.out.println("代理音频流请求: " + url);
            
            // 验证URL
            if (!isSupportedMusicUrl(url)) {
                System.err.println("不支持的音乐URL: " + url);
                return ResponseEntity.badRequest().build();
            }

            // 设置请求头，模拟浏览器请求
            HttpHeaders headers = new HttpHeaders();
            headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
            headers.set("Referer", getRefererByUrl(url));
            headers.set("Accept", "audio/*, application/octet-stream");
            headers.set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
            headers.set("Cache-Control", "no-cache");
            headers.set("Pragma", "no-cache");
            
            HttpEntity<String> entity = new HttpEntity<>(headers);
            
            // 获取音频数据，支持重定向
            System.out.println("发起代理请求...");
            ResponseEntity<byte[]> response = null;
            String finalUrl = url;
            int redirectCount = 0;
            int maxRedirects = 5;
            
            while (redirectCount < maxRedirects) {
                try {
                    response = restTemplate.exchange(
                        finalUrl, 
                        HttpMethod.GET, 
                        entity, 
                        byte[].class
                    );
                    
                    System.out.println("代理请求响应状态: " + response.getStatusCode());
                    
                    // 检查是否是重定向响应
                    if (response.getStatusCode().is3xxRedirection()) {
                        String locationHeader = response.getHeaders().getFirst("Location");
                        if (locationHeader != null) {
                            System.out.println("检测到重定向: " + locationHeader);
                            finalUrl = locationHeader;
                            redirectCount++;
                            continue;
                        }
                    }
                    
                    break; // 成功获取响应，跳出循环
                    
                } catch (HttpClientErrorException | HttpServerErrorException e) {
                    System.err.println("HTTP错误: " + e.getStatusCode() + " - " + e.getMessage());
                    throw e;
                } catch (ResourceAccessException e) {
                    System.err.println("网络访问错误: " + e.getMessage());
                    throw e;
                }
            }
            
            if (response == null) {
                System.err.println("达到最大重定向次数: " + maxRedirects);
                return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).build();
            }
            
            System.out.println("最终URL: " + finalUrl);
            System.out.println("响应内容长度: " + (response.getBody() != null ? response.getBody().length : 0));

            // 检查响应内容
            byte[] audioData = response.getBody();
            if (audioData == null || audioData.length == 0) {
                System.err.println("音频数据为空");
                
                // 尝试获取响应头信息
                HttpHeaders responseHeaders = response.getHeaders();
                System.out.println("响应头信息:");
                responseHeaders.forEach((key, value) -> 
                    System.out.println("  " + key + ": " + value));
                
                return ResponseEntity.noContent().build();
            }

            // 设置响应头
            HttpHeaders responseHeaders = new HttpHeaders();
            responseHeaders.setContentType(MediaType.parseMediaType("audio/mpeg"));
            responseHeaders.set("Cache-Control", "public, max-age=3600");
            
            System.out.println("成功代理音频流，数据长度: " + audioData.length);
            return new ResponseEntity<>(audioData, responseHeaders, HttpStatus.OK);
            
        } catch (Exception e) {
            System.err.println("音频流代理失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 检查URL是否可访问
     */
    @PostMapping("/check")
    public ResponseEntity<?> checkAudioUrl(@RequestBody Map<String, String> request) {
        try {
            String url = request.get("url");
            
            if (url == null || url.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("URL不能为空"));
            }

            boolean isAccessible = checkUrlAccessibility(url);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("accessible", isAccessible);
            response.put("url", url);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("检查URL失败: " + e.getMessage()));
        }
    }

    /**
     * 验证是否为支持的音乐URL
     */
    private boolean isSupportedMusicUrl(String url) {
        if (url == null) return false;
        
        String[] supportedDomains = {
            "music.163.com",
            "y.qq.com", 
            "stream.qqmusic.qq.com",
            "kugou.com",
            "kuwo.cn",
            "soundcloud.com"
        };
        
        for (String domain : supportedDomains) {
            if (url.contains(domain)) {
                return true;
            }
        }
        
        // 检查是否为直接的音频文件URL
        return url.toLowerCase().matches(".*\\.(mp3|wav|flac|m4a|aac|ogg)$");
    }

    /**
     * 根据平台处理URL
     */
    private String processUrlByPlatform(String url, String platform) {
        switch (platform) {
            case "netease":
                return processNeteaseUrl(url);
            case "qq":
                return processQQUrl(url);
            default:
                return url;
        }
    }

    /**
     * 处理网易云音乐URL
     */
    private String processNeteaseUrl(String url) {
        // 网易云音乐的URL通常可以直接使用
        // 但可能需要添加特殊的参数或处理
        return url;
    }

    /**
     * 处理QQ音乐URL
     */
    private String processQQUrl(String url) {
        // QQ音乐可能需要特殊处理
        return url;
    }

    /**
     * 根据URL获取合适的Referer
     */
    private String getRefererByUrl(String url) {
        if (url.contains("music.163.com")) {
            return "https://music.163.com/";
        } else if (url.contains("y.qq.com")) {
            return "https://y.qq.com/";
        } else if (url.contains("kugou.com")) {
            return "https://www.kugou.com/";
        } else if (url.contains("kuwo.cn")) {
            return "https://www.kuwo.cn/";
        }
        return "";
    }

    /**
     * 检查URL可访问性
     */
    private boolean checkUrlAccessibility(String url) {
        try {
            URL audioUrl = new URL(url);
            URLConnection connection = audioUrl.openConnection();
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
            
            String contentType = connection.getContentType();
            return contentType != null && contentType.startsWith("audio/");
            
        } catch (IOException e) {
            return false;
        }
    }

    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        return response;
    }
} 